/**
 * 【常用的一些服务】
 * Created by mosaic101 on 2016/8/6.
 */
define(function (require, exports, module) {
  'use strict';
  module.exports = function (app) {
    app.factory("MHService", ["$http", "$timeout", "localStorageService", "$cacheFactory", "$q", "$filter", "$location",
      function ($http, $timeout, localStorageService, $cacheFactory, $q, $filter, $location) {
        var toast = require('./mh-toast');
        var HTTPStatus = require('./http-data');
        var loading = angular.element('#loadingModal');
        var localCache = $cacheFactory('location');

        /**
         * 计算当前分页数据情况
         * @param data
         * @param pageSize
         * @param pageIndex
         */
        function pagingCalc(data, pageIndex, pageSize) {
          var tempData = data['datas'] || data['data'];
          var _return = {
            code: 0,
            data: tempData
          };
          if (data['page']) {
            var totalCount = data['page'].count;
            //1、当前已经获取到的分页数据计算；当前页面数据长度+（当前页面-1）x分页大小
            var nowCount = tempData.length + (pageIndex - 1) * pageSize;
            _return.hasNext = (nowCount < totalCount);//数据没有获取完
            _return.hasBefore = (pageIndex <= 1);//当前是否是第一页
          } else {
            _return.hasNext = false;//数据没有获取完
            _return.hasBefore = false;//当前是否是第一页
          }
          return _return;
        }
        /**
         * 弹出加载框
         * @param flag
         * @param message
         */
        function loadingAlert(flag, message) {
          if (message) {
            angular.element("#loading-title").text(message);
          }
          flag ? loading.modal({closeViaDimmer: false}) : loading.modal('close');
        }

        return {
          URL: HTTPStatus.URL,
          /**
           * 弹出"正在加载..."框
           * @param flag
           */
          loading: function (flag, msg) {
            loadingAlert(flag, msg);
          },
          /**
           * 修改页面title
           * @param title
           */
          setTitle: function (title) {
            var $body = angular.element('body');
            document.title = title;
            // hack在微信等webview中无法修改document.title的情况
            var iframe = angular.element('<iframe src="images/favicon.ico"></iframe>').on('load', function () {
              $timeout(function () {
                iframe.off('load').remove();
              });
            }).appendTo($body);
          },
          Toast: function (msg) {
            toast.show(msg);
          },
          /**
           * 登录失败录成功清空所有数据
           */
          globalClearAll: function () {
            return localStorageService.clearAll();
          },
          /**
           * 分页查询
           * @param url
           * @param pageSize
           * @param pageIndex
           * @param callback
           */
          pageQuery: function (config, callback) {
            if (!localStorageService.get("isLogin")) {
              //未登录
              toast.show('请登录');
              $timeout(function () {
                $location.path('/login');
              }, 500);
              return;
            }
            loadingAlert(true, '正在获取...');
            var tIndex = config.pageIndex, tSize = config.pageSize ? config.pageSize : 15;
            var pattern = config.url.match('(id=|aid=)'), tUrl = '';
            if (pattern) {
              tUrl = config.url + '&page=' + tIndex + '&size=' + tSize;
            } else {
              tUrl = config.url + '?page=' + tIndex + '&size=' + tSize;
            }
            $http.get(tUrl).success(function (data) {
//              console.log(data);
              if (data['success']) {
                //成功获取数据，计算分页情况
                var result = pagingCalc(data, tIndex, tSize);
                //if (data.procedures) {
                result.procedures = data.procedures;
                //}
                //有流程相关数据
                result.gprid = data.gprid;
                result.isStart = data.isStart;
                result.ischeckedUser = data.ischeckedUser;
                callback(result);
              } else {
                //获取失败，展示错误信息
                toast.show(data['msg']);
              }
              loadingAlert(false);
            }).error(function (data) {
              //查询失败，展示错误信息
              loadingAlert(false);
              if (data.match('<h1>404 Not Found</h1>')) {
                toast.show('请登录');
                $timeout(function () {
                  $location.path('/login');
                }, 500);
              } else {
                toast.show('操作失败，请刷新重试 -s');
              }
            });
          },
          /**
           * get请求
           * @param config
           * @param callback
           */
          getReq: function (config, callback) {
            //if (!localStorageService.get("isLogin")) {
            //  //未登录
            //  toast.show('请登录');
            //  $timeout(function () {
            //    $location.path('/login');
            //  }, 500);
            //  return;
            //}
            //loadingAlert(true, '正在获取...');
            $http.get(config.url).success(function (result) {
              if (result['tag'] == 'success') {
                callback(result.data);
              } else {
                toast.show(result['message']);
              }
              //loadingAlert(false);
            }).error(function (data) {
              //查询失败，展示错误信息
              //loadingAlert(false);
              //if (data.match('<h1>404 Not Found</h1>')) {
              //  toast.show('请登录');
              //  $timeout(function () {
              //    $location.path('/login');
              //  }, 500);
              //} else {
              //  toast.show('操作失败，请刷新重试 -s');
              //}
            });
          },
          /**
           * post请求
           * @param config
           * @param callback
           */
          postReq: function (config, callback) {
            //if (!localStorageService.get("isLogin")) {
            //  //未登录
            //  toast.show('请登录');
            //  $timeout(function () {
            //    $location.path('/login');
            //  }, 500);
            //  return;
            //}
            //loadingAlert(true, '正在提交...');
            //console.log(config._req);
            $http.post(config.url, config._req).success(function (result) {
              if (result['tag'] == 'success') {
                callback(result.data);
              } else {
                toast.show(result['message']);
              }
              //loadingAlert(false);
            }).error(function (data) {
              //查询失败，展示错误信息
              //toast.show('操作失败，请刷新重试 -s');
              //loadingAlert(false);
              //if (data.match('<h1>404 Not Found</h1>')) {
              //  $timeout(function () {
              //    $location.path('/login');
              //  }, 500);
              //}
            });
          },
          /**
           * 获取一些全局的数据
           * @param isSave
           * @param data
           * @returns {*}
           */
          globalData: function (isSave, data) {
            if (isSave) {
//              console.log(data);
              localStorageService.set(data.key, data.value);
            } else {
              return localStorageService.get(data.key);
            }
          },
          /**
           * cache中存储数据
           * @param isSave
           * @param data
           */
          cacheData: function (isSave, data) {
            if (isSave) {
              localCache.put(data.key, data.value);
            } else {
              return localCache.get(data.key);
            }
          },
          /**
           * 清空所有数据
           * @param key
           */
          removeStorage: function (key) {
            var defer = $q.defer();
            (localStorageService.remove(key)) ? defer.resolve() : defer.reject();
            return defer.promise;
          },
          queryLocation: function (callback) {
            // 获取用户位置，先查看本地cache，若没有则请求定位
            if (localCache.get('currentLocation')) {
              callback(localCache.get('currentLocation'));
            } else {
              var geolocation = new BMap.Geolocation();
              geolocation.getCurrentPosition(function (r) {
                if (this.getStatus() == BMAP_STATUS_SUCCESS) {
                  localCache.put('currentLocation', r.point);
                  callback(r.point);//将当前位置作为参数传递给回调函数
                  localStorageService.set("currentStreet", r.address.street);
                } else {
                  toast.show('failed' + this.getStatus());
                }
              });
            }
            //var r = {
            //  point: new BMap.Point(120.329265, 31.686326),
            //  address: {
            //    street: "凤翔新城"
            //  }
            //};
            //callback(r.point);
            //localStorageService.set("currentStreet", r.address.street);
          },
          setCurrentMarker: function (marker) {
            //保存marker信息
            if (localStorageService.isSupported) {
              localStorageService.set("currentMarker", marker);
            } else {
              return "browser does not support localStorage";
            }
          },
          messageFormat: function (messages) {
            var defer = $q.defer(),//promise
              _result = angular.copy(messages),
              _messages = angular.copy(messages['data']),//消息列表
              _return = [],//返回的数据
              currentTime = null,//当前的时间
              tMsg = [];//当前时间下的消息列表
            angular.forEach(_messages, function (obj, index, array) {
              if (index === 0) {
                //第一条消息，记录当前时间
                currentTime = $filter('date')(obj.sendtime.time, 'yyyy-MM-dd');
                tMsg.push({message: obj.content, time: $filter('date')(obj.sendtime.time, 'HH:mm:ss')});
              } else if ($filter('date')(obj.sendtime.time, 'yyyy-MM-dd') === currentTime) {
                //同一时间(天)下的消息
                tMsg.push({message: obj.content, time: $filter('date')(obj.sendtime.time, 'HH:mm:ss')});
              } else {
                //新的时间下的消息了
                _return.push({time: currentTime, content: angular.copy(tMsg)});
                currentTime = $filter('date')(obj.sendtime.time, 'yyyy-MM-dd');//时间重新赋值
                tMsg.removeAll();//清空消息列表
                tMsg.push({message: obj.content, time: $filter('date')(obj.sendtime.time, 'HH:mm:ss')});//放入最新消息
              }
              if (index === _messages.length - 1) {
                //最后一条消息,如果_return为0，表示只有今天的消息
                if (_return.length === 0) {
                  _return.push({time: currentTime, content: angular.copy(tMsg)});
                }
                _result['data'] = _return;
                defer.resolve(_result);
              }
            });
            return defer.promise;
          },
          feedManage: function(criteria, callback) {
            //拉取提料数据
            var URL = criteria.URL;
            $http.get(URL).success(function(data) {
              // console.log(data);
              if(data.success) {
                callback(data);
              }
            })
          }
        }
      }]);
  };
});
